package com.example.crawlerjava.handler;

import cn.hutool.json.JSONUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局返回值处理
 */
@Slf4j
@RestControllerAdvice
public class GlobalBodyAdvice implements ResponseBodyAdvice<Object> {
    @Resource
    private HttpServletRequest request;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 排除Swagger的API请求
        String requestURI = request.getRequestURI();
        // 此处先写死，后续做成配置化
        return !requestURI.contains("/swagger-ui/") && !requestURI.contains("/v3/api-docs");
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request,
                                  ServerHttpResponse response) {
        //如果是字符串
        if (body instanceof String) {
            return JSONUtil.toJsonStr(ResponseResult.success(body));
            //如果已经是包装类，就直接返回
        } else if (body instanceof ResponseResult) {
            return body;
        }
        //默认返回成功
        return ResponseResult.success(body);
    }
}
